var mongoose = require('mongoose');
const DataModel = require('../models/news.model');
const Comment = require('../models/comment.model');

var async = require('async');

exports.create = function(req,res,next){
	const dataModel = new DataModel(req.body);

	dataModel.save()
	.then(data=>{
		res.json(data);
	})
}

exports.get = function(req,res,next){
	var id = req.params.id;

	DataModel.findById(id, function (err, data) {
	  res.json(data);
	})
}


exports.update = function(req,res,next){
	const id = req.params.id;

	DataModel.findByIdAndUpdate(id, {$set: req.body}, {new:false})
	.then(data=>{
		res.json(data);
	})

}

exports.remove = function(req,res,next){
	const id = req.params.id;

	if(id){
		DataModel.findByIdAndRemove(id,function(err,data){
			//res.json(data);
			res.json({"msg":"deletes success","status":200});
		})
	}else{
		res.json({"msg":"deletes fail","status":404});
	}
	
}

exports.deletes = function(req,res,next){
	var ids = req.body.ids;
	
	if(ids.length>0){
		console.log(ids.split(','))
		DataModel.remove({_id: {$in: ids.split(',')}})
		.then(data=>{
			res.json({"msg":"deletes success","status":200});
		})
	}else{
		res.json({"msg":"deletes fail","status":404});
	}
}

exports.list = function(req,res,next){
	var page = (req.body.page) ? req.body.page : 1;
	var limit = (req.body.limit) ? req.body.limit : 5;

	var queryCondition = {};
	if(req.body.title && req.body.title.trim().length>0){
		title = req.body.title;
		queryCondition = {
			"title" : new RegExp(title, 'i')
		}
	}


	if(req.body.cateId && req.body.cateId.trim().length>0){
		cateId = req.body.cateId;
		// Object.assign对象合并
		queryCondition = Object.assign(queryCondition,
			{
				cateId: cateId
			}
		)
	}
	
	DataModel.paginate(queryCondition, { page: parseInt(page), limit: parseInt(limit) }, function(err, result) {
	 	// result.rows = result.docs;
	 	// delete result.docs;
	 	// res.json(result)

	 	async.map(result.docs,function(news,done){ // callback修改成done

	 		Comment.count({newsId: news._id},function(err,count){
	 			if(err){
	 				return;
	 			}else{
	 				news.commentCount = count;
	 				done();
	 			}
	 		})

	 	},function(err){
	 	 result.rows = result.docs;
	 	 delete result.docs;
	 		res.json(result)
	 	})

	});
	
}
